package fr.irstv.kmeans;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;
import java.util.List;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import com.sun.org.apache.xerces.internal.parsers.DOMParser;

import fr.irstv.dataModel.DataPoint;
import fr.irstv.dataModel.MkDataPoint;
import fr.irstv.dataModel.Segment;

/**
 * specific class for reading MK points data files
 * see in XML file, no DTD or schema yet
 * 
 * @author moreau
 *
 */
public class DataMk extends DataCorpus {

	public DataMk(String fileName) throws IOException {
		super();
		
		readXmlMk(fileName);
		// TODO Auto-generated constructor stub
	}
	/**
	 * reading datafile
	 * 
	 * @author moreau
	 * @version 1
	 * 
	 * @param fileName name of the file
	 * 
	 */
	public void readXmlMk(String url) {
		Document document = null;
	    try {
			//URL urlDesc = new URL(url);
			//URLConnection connection = urlDesc.openConnection();
			//InputStream flux = connection.getInputStream();
			BufferedReader bf = new BufferedReader(new FileReader(url));
	        DOMParser parser = new DOMParser();
	        parser.parse(new InputSource(bf));
	        document = parser.getDocument();
		    NodeList nl = document.getElementsByTagName("Coordonnees");
		    System.out.println("--debug-- "+nl.getLength()+" segments in file");
		    for (int i=0 ; i<nl.getLength() ; i++) {
		    	DataPoint dp1 = new DataPoint(2);
		    	DataPoint dp2 = new DataPoint(2);
		    	Node n = nl.item(i);
		    	NamedNodeMap nnm = n.getAttributes();
		    	dp1.set(0, Double.parseDouble(nnm.getNamedItem("Segments-xp1").getNodeValue()));
		    	dp1.set(1, Double.parseDouble(nnm.getNamedItem("Segments-yp1").getNodeValue()));
		    	dp2.set(0, Double.parseDouble(nnm.getNamedItem("Segments-xp2").getNodeValue()));
		    	dp2.set(1, Double.parseDouble(nnm.getNamedItem("Segments-yp2").getNodeValue()));
		    	Segment s = new Segment(dp1,dp2,null);
		    	MkDataPoint mkp = new MkDataPoint(s.getHPoint(),s);
		    	corpus.add(mkp);
		    }
	    } catch (Exception e) {
	    	System.out.println("damn it!");
	        e.printStackTrace();
	    }
	}
}
